export default class Controller {
  constructor(stageList) {
    this.name = "controller";
    this.setStageList(stageList);
    this.setChainList();
  }
  run() {
    this.listen();
  }
  setChainList() {
    this.chainList = [];
  }
  setStageList(stageList) {
    this.stageList = stageList;
  }
  listen() {
    document.onkeydown = event => {
      let e = event || window.event || arguments.callee.caller.arguments[0];

      /* 这是下按键 */
      if (e && e.keyCode === 40) {
        this.dealDown();
      }

      /* 这是上按键 */
      if (e && e.keyCode === 38) {
        this.dealUp();
      }

      /* 这是左按键 */
      if (e && e.keyCode === 37) {
        this.dealLeft();
      }
      /* 这是右按键 */
      if (e && e.keyCode === 39) {
        this.dealRight();
      }
    };
  }
  nextList() {
    const temp = this.stageList.shift();
    this.chainList.push(temp);
  }
  beforeList() {
    const temp = this.chainList.pop();
    this.stageList.unshift(temp);
  }
  isLast() {
    return this.stageList.length === 0;
  }
  isFirst() {
    return this.chainList.length < 2;
  }
  dealDown() {
    console.log("is last", this.isLast());
    if (this.isLast()) return;
    this.nextList();
    this.goForward();
  }
  dealUp() {
    if (this.isFirst()) return;
    this.beforeList();
    this.goBack();
  }
  dealLeft() {
    this.dealUp();
  }
  dealRight() {
    this.dealDown();
  }
  goForward() {
    const next = this.chainList.slice(-1)[0];
    const forward = this.chainList.slice(-2, -1)[0];
    next.show();
    next.run();

    forward && forward.hide();
    forward && forward.stopWord();
  }
  goBack() {
    const forward = this.stageList[0];
    const next = this.chainList.slice(-1)[0];
    next.show();
    next.run();

    forward && forward.hide();
    forward && forward.stopWord();
  }
}
